﻿using DataAccess;
using DataEntity;
using IntelligentQuery.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Tools;

namespace WebUI.Controllers
{
    public class UserController : Controller
    {
        //
        // GET: /User/
        private DataContext db = new DataContext();
        private Encrypt encrypt = new Encrypt();
        private IEntityRepository<SysUser> UserRepository;
        public UserController()
        {
            UserRepository = new EntityRepository<SysUser>(db);
        }
        public ActionResult Index()
        {
            return View();
        }
        #region  json返回数据
        /// <summary>
        /// 公司信息
        /// </summary>
        /// <param name="page"></param>
        /// <param name="rows"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult UserJson(int? page, int? rows, string model)
        {
            int Page = page ?? 1;
            int Rows = rows ?? 10;
            QueryModel QModel = null;
            Dictionary<string, object> JsonObj = new Dictionary<string, object>();
            if (!string.IsNullOrWhiteSpace(model))
            {
                QModel = IntelligentQuery.AjaxQueryConverter.ToQueryModel(model);
            }


            var user = UserRepository.Get(QModel).Where(n => n.BeLock == false && n.IsAdmin == false).ToList();

            JsonObj.Add("total", user.Count());
            JsonObj.Add("rows", user.OrderByDescending(p => p.ID)
                    .Skip((Page - 1) * Rows)
                   .Take(Rows).Select(s => new { s.ID, s.UserName, s.RealName, s.Sex, s.Mobile, s.Password, s.Email, s.Remark, s.BeLock, s.Tel,RoleName=s.SysRole.Name }));


            return JsonHelper.JsonEx(JsonObj);
        }

        #endregion
        #region 操作数据
        /// <summary>
        /// 新建/编辑页
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult CreateEdit(int id = 0)
        {
            var model = new SysUser();

            if (id != 0)
            {
                model = UserRepository.GetByKey(id);
            }
            var sysUser=db.SysRoles.Where(n=>!n.BeLock).FirstOrDefault();
            ViewBag.SysRoleID = model.SysRoleID==0?sysUser!=null?sysUser.ID:0:model.SysRoleID;
            return PartialView(model);
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="role"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Save(SysUser model)
        {
            try
            {

                if (model.ID == 0)
                {
                    model.Password = encrypt.Encode("123456");
                    UserRepository.Insert(model);
                }
                else
                {
                    SysUser user = UserRepository.GetByKey(model.ID);

                    user.SysRoleID = model.SysRoleID;
                    user.Email = model.Email;
                    user.Mobile = model.Mobile;
                    user.RealName = model.RealName;
                    user.Sex = model.Sex;
                   
                    user.Tel = model.Tel;
                    user.Remark = model.Remark;

                    UserRepository.Update(user);

                }


                return Json(new { success = true });
            }
            catch (Exception e)
            {
                return Json(new { msg = e.Message });
            }
        }
        /// <summary>
        /// 单个删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult SingleDelete(int id)
        {
            try
            {
                var user = UserRepository.GetByKey(id);
                user.BeLock = true;
                UserRepository.Update(user);

                return Json(new { success = true });
            }
            catch (Exception e)
            {
                return Json(new { msg = e.Message });
            }
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult BatchDelete(string ids)
        {
            try
            {
                List<string> list_id = ids.Split(',').ToList();
                var userList = UserRepository.Get().ToList().Where(u => list_id.Contains(u.ID.ToString())).ToList();
                foreach (var user in userList)
                {
                    user.BeLock = true;

                }
                UserRepository.Update(userList);
                return Json(new { success = true });
            }
            catch (Exception e)
            {
                return Json(new { msg = e.Message });
            }
        }


        #endregion

        #region 验证函数
        /// <summary>
        /// 校验userno是否已经存在
        /// 不存在 返回true
        /// 存在 返回false
        /// </summary>
        /// <param name="userno"></param>
        /// <returns></returns>
        public string AjaxCheckAddUserNotExist(string UserName)
        {
            if (UserRepository.Get().Any(u => (u.UserName == UserName)))
            {
                return "false";
            }
            else
            {
                return "true";
            }
        }

        /// <summary>
        /// 校验userno是否已经存在
        /// 不存在 返回true
        /// 存在 返回false
        /// </summary>
        /// <param name="userno"></param>
        /// <returns></returns>
        public bool AjaxCheckUpdateUserNotExist(string Value, int Key)
        {
            return !UserRepository.Get().Any(u => (u.UserName== Value));
        }
        #endregion
        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }

    }
}
